using System;
using System.Web;
using SoftwareMonkeys.Scriptech.Diagnostics;

namespace SoftwareMonkeys.Scriptech.Scripts
{
	public class ScriptHttpHandler : IHttpHandler
	{
		public bool IsReusable {
			get { return false; }
		}

		private ScriptRouteHandler routeHandler;

		public ScriptHttpHandler (ScriptRouteHandler routeHandler)
		{
			this.routeHandler = routeHandler;
		}

		public void ProcessRequest (HttpContext context)
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Processing request via script HTTP handler."))
			{
				if (routeHandler.VirtualPath != null && routeHandler.VirtualPath != String.Empty)
				{
					string path = routeHandler.VirtualPath;
					
					if (path == null || path == String.Empty)
						throw new Exception("VirtualPath property must be set.");
					
					LogWriter.Debug("Path: " + path);
					
					// TODO: Check if query string is needed
					string queryString = HttpContext.Current.Request.Url.Query;
					
					LogWriter.Debug("Query string: " + queryString);
					
					try
					{
						//using (TimeoutExtender extender = TimeoutExtender.NewMinutes(60))
						//{
							Go(path, true);
						//}
						
					}
					catch (Exception ex)
					{
						LogWriter.Error(ex);
				
						throw;
					}
				}
			}
		}
		
		public void Go(string path, bool persistForm)
		{
			Go(HttpContext.Current, path, persistForm);
		}
		
		public void Go(HttpContext context, string path, bool persistForm)
		{			
			if (FrameworkChecker.IsMono)
			{
	//		context.Response.Redirect(path, false); // shows ugly urls in browser
				context.Server.Execute(path, persistForm);
	//			context.Server.Transfer(path, persistForm); // works in linux but not on windows .NET.
	//			context.RewritePath(path);
			}
			else
			{
				//context.Response.Redirect(path, true); // shows ugly urls in browser
				context.Server.Execute(path, persistForm);
			}

			// other redirect approaches							
			//HttpContext.Current.Server.Execute(newPath, false); // doesn't seem to work on linux
			//HttpContext.Current.Response.Redirect(path); // works on windows .NET but not Mono/Linux	
		}
		
	}
}

